package com.hotel.customersystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.status.ResultMsg;
import com.common.status.StatusCode;
import com.common.utils.ResultUtils;
import com.common.utils.ResultVo;
import com.hotel.config.jwt.JwtConfig;

import com.hotel.customersystem.pojo.CustomerUser;
import com.hotel.customersystem.pojo.LoginUserVo;
import com.hotel.customersystem.pojo.UserVo;
import com.hotel.customersystem.service.CustomerUserService;
import com.hotel.utils.phone.PhoneSendCode;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * (CustomerUser)表控制层
 *
 * @author makejava
 * @since 2022-09-30 16:33:30
 */
@Api(value = "CustomerUserController",tags = {"个人中心用户模块"})
@RestController
@RequestMapping("customerUser")
public class CustomerUserController {
    /**
     * 服务对象
     */
    private final CustomerUserService customerUserService;
    private final RedisTemplate redisTemplate;
    public CustomerUserController(CustomerUserService customerUserService,RedisTemplate redisTemplate) {
        this.customerUserService = customerUserService;
        this.redisTemplate = redisTemplate;
    }


    @Resource
    private JwtConfig jwtConfig;


    /**
     * 头像上传
     * @param imgUrl
     * @param userAdmin
     * @return
     */
    @ApiOperation(value = "头像上传(根据用户账号)")
    @PostMapping("/uploadHeadPortrait")
    public ResultVo<Boolean> uploadHeadPortrait(@RequestParam String userAdmin,@RequestParam String imgUrl) throws Exception {
        Boolean flag = customerUserService.uploadHeadPortrait(userAdmin,imgUrl);
        if (flag) {
//            webSocketProcess.sendAllMessage("上传成功!");
            return ResultUtils.success(ResultMsg.SUCCESS_MSG,StatusCode.SUCCESS_CODE,true);
        }
        else {
//            webSocketProcess.sendAllMessage("上传失败!");
            return ResultUtils.error(ResultMsg.DATA_NULL,StatusCode.SYSTEM_ERROR_CODE, false);
        }
    }

    @ApiOperation(value = "用户列表")
    @GetMapping("/getCustomerUserList")
    public ResultVo<List<CustomerUser>> getCustomerUserList() {
        List<CustomerUser> list = customerUserService.list();
        if (list.size()!=0) return ResultUtils.success(ResultMsg.SUCCESS_MSG, StatusCode.SUCCESS_CODE,list);
        else return ResultUtils.error(ResultMsg.ERROR_MSG, StatusCode.SYSTEM_ERROR_CODE,list);
    }

    /**
     * 登录
     * @return
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/userLogin")
    public ResultVo<LoginUserVo> userLogin(@RequestBody UserVo user) throws Exception {
        System.out.println("正在执行登录...");
        LoginUserVo result = customerUserService.login(user);
        if (result != null) {
            return ResultUtils.success(ResultMsg.LOGIN_SUCCESS,StatusCode.SUCCESS_CODE,result);
        }
        else {
            return ResultUtils.success(ResultMsg.LOGIN_FAIL,StatusCode.SYSTEM_ERROR_CODE,null);
        }
    }

    /**
     * 注册
     * @return
     */
    @ApiOperation(value = "用户注册")
    @PostMapping("/userRegister")
    public ResultVo<CustomerUser> userRegister(@RequestBody CustomerUser user) {
//        Boolean flag = customerUserService.register(user);
        user.setStandby02("https://img2.woyaogexing.com/2022/11/06/51140bda09401a61!400x400.jpg");
        boolean flag = customerUserService.save(user);
        if (flag) return ResultUtils.success(ResultMsg.REGISTER_SUCCESS,StatusCode.SUCCESS_CODE,null);
        else return ResultUtils.success(ResultMsg.REGISTER_FAIL,StatusCode.SYSTEM_ERROR_CODE,null);
    }

    /**
     * 获取用户状态
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取用户状态")
    @GetMapping("/checkToken")
    public ResultVo<Claims> checkToken(HttpServletRequest request) throws Exception {
        // 从请求头部中获取token
        String token = request.getHeader("token");
        System.out.println(token);
        boolean flag = jwtConfig.checkToken(token);
        if (flag) return ResultUtils.success(ResultMsg.SUCCESS_MSG,StatusCode.SUCCESS_CODE,true);
        else return ResultUtils.error(ResultMsg.TOKEN_INVALID,StatusCode.SYSTEM_ERROR_CODE,false);
    }

    /**
     * 获取手机验证码
     * @param phone
     * @return
     */
    @ApiOperation(value = "获取手机验证码")
    @PostMapping("/getPhoneCode")
    public ResultVo<String> getPhoneCode(@RequestParam String phone) {
        //1.从redis中获取验证码，如果缓存中有的话直接返回，没有的话从阿里云发送获取
        String code = (String) redisTemplate.opsForValue().get(phone);
        if (Strings.isEmpty(code)) {
            code = PhoneSendCode.getSixBitRandom(); // 生成6为验证码
            Map<String,Object> map = new HashMap<>();
            map.put("code",code);
            Boolean flag = customerUserService.sendPhoneCode(map, phone);
            if (flag)
                // 验证码放入缓存中，有效期1分钟     key   value   过期时常
                redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
            else
                return ResultUtils.error(ResultMsg.PHONE_CODE_FAIL,StatusCode.PHONE_CODE_FAIL);
        }
        return ResultUtils.success(ResultMsg.PHONE_CODE_SUCCESS,StatusCode.PHONE_CODE_SUCCESS,code);
    }

    /**
     * 手机验证码登录
     * @param phone
     * @param code
     * @return
     */
    @ApiOperation(value = "手机验证码登录")
    @PostMapping("/loginByPhoneCode")
    public ResultVo<LoginUserVo> loginByPhoneCode(@RequestParam String phone, @RequestParam String code) {
        // 判断缓存里面是否有验证码
        if (!code.equals(redisTemplate.opsForValue().get(phone))) return ResultUtils.error(ResultMsg.PHONE_CODE_NONE,StatusCode.PHONE_CODE_FAIL);
        LoginUserVo loginUserVo = customerUserService.loginByPhoneCode(phone, code);
        if (loginUserVo != null) return ResultUtils.success(ResultMsg.LOGIN_SUCCESS,StatusCode.SUCCESS_CODE,loginUserVo);
        else return ResultUtils.error(ResultMsg.LOGIN_FAIL,StatusCode.SYSTEM_ERROR_CODE,null);
    }

    @ApiOperation(value = "根据用户id查询用户信息")
    @GetMapping("/getUserInfoByUserId")
    public ResultVo<CustomerUser> getUserInfoByUserId(@RequestParam Integer userId) {
        LambdaQueryWrapper<CustomerUser> ldq = new LambdaQueryWrapper<>();
        ldq.eq(CustomerUser::getUserId,userId);
        CustomerUser one = customerUserService.getOne(ldq);
        if (one != null)
            return ResultUtils.success(ResultMsg.SUCCESS_MSG,StatusCode.SUCCESS_CODE,one);
        else
            return ResultUtils.error(ResultMsg.ERROR_MSG,StatusCode.SYSTEM_ERROR_CODE,null);
    }

}

